<?php
/**
 * 通联支付单 推送
 */
namespace ordersync;

use app\common\model\Area;
use request\Request;
use request\RequestException;
use RobRichards\XMLSecLibs\XMLSecurityDSig;
use RobRichards\XMLSecLibs\XMLSecurityKey;

class AllinpaySyncRequest extends Request {

    protected $method = 'post';
    protected $apiMethodName = 'uploadFiles';
    protected static $priKey;
    protected static $cert;
    protected $paymentInfo = [];

    public function __construct()
    {
        $url = 'https://service.allinpay.com/customs/pvcapply';
        $this->setUrl($url);

        // 初始化支付配置
        // 通联微信支付
        $logic_payment = model('payment', 'logic');
        $result = $logic_payment->getPaymentInfo('allinpay');
        if (!$result['code']) {
            $this->error($result['msg']);
        }
        $this->paymentInfo = $result['data']['payment_config'];
    }

    /**
     * 请求数据转化
     * @param $order
     * @param int $dimension // 数组维度
     * @return array
     * @throws RequestException
     */
    protected function requestTransfer($order, $dimension = 1)
    {
        $xml = $this->generateXML($order);

        echo $xml;

        return [
            'data' => base64_encode($xml)
        ];
    }

    /**
     * 生成压缩包
     * @param $order
     * @return string
     * @throws RequestException
     */
    private function generateXML($order) {

        $body = [
            'CUSTOMS_CODE' => 'HG023',    // 海关类别，详见4.1
            'PAYMENT_CHANNEL' => 2,    // 详见2.3
            'CUS_ID' => $this->paymentInfo['allinpay_mch_id'],    // 在支付渠道进行支付用的商户号（注;如果对接云商通，这里填写云商通系统给大B分配的应用号）
            'PAYMENT_DATETIME' => date('YmdHis', $order['payment_time']),    // 时间格式 yyyyMMddHH24mmss
            'MCHT_ORDER_NO' => $order['order_sn'],    // 商户平台订单号
            'PAYMENT_ORDER_NO' => $order['trade_no'],    // 支付系统订单号
            'PAYMENT_AMOUNT' => $order['order_amount'] * 100,    // 单位为分
            'CURRENCY' => 156,    // 详见2.2 固定为人民币
            'ESHOP_ENT_CODE' => config('customs_config.ebpCode'),    // 海关分配的电商平台代码
            'ESHOP_ENT_NAME' => config('customs_config.ebpName'),    // 海关分配的电商平台名称
            'PAYER_NAME' => $order['extend_order_common']['reciver_name'],    // 支付人姓名
            'PAPER_TYPE' => '01',    // 01：身份证
            'PAPER_NUMBER' => $order['extend_order_common']['reciver_info']['id_card_no'],    // 支付人证件号码
            'PAPER_PHONE' => $order['extend_order_common']['reciver_info']['mob_phone'],    // 支付人手机号
            'MAIN_PAYMENT_ORDER_NO' => '',    // 支付系统流水号
        ];

        $body_xml = $this->arrayToXml($body, null, null, 'BODY');

        $head = [
            'VERSION' => 'v5.6',    // 版本号
            'VISITOR_ID' => 'MCT',     // 接入方编号，包括'MCT'.'TLT','ETS','BIZ'.'SYB'.'GZF'。商户送'MCT'
            'MCHT_ID'    => '109215321909005',   // 报关用的商户号
            'ORDER_NO'   => $order['order_sn'], // 流水号，无业务含义
            'TRANS_DATETIME'    => date('YmdHis'),  // 发送时间
            'CHARSET'    => 1,  // 默认值1，UTF-8
            'SIGN_TYPE'  => 1,   // 默认值1，MD5签名
            'SIGN_MSG'   => strtoupper(md5($body_xml . '<key>1234567890</key>')), // 签名密文
        ];

        return $this->arrayToXml([
            'HEAD' => $head,
            'BODY' => $body,
        ], null, null, 'PAYMENT_INFO');
    }

    /**
     * 组装XML
     * @param array $arr
     * @param null $dom
     * @param null $node
     * @param string $root
     * @param bool $cdata
     * @return string
     */
    public function arrayToXml($arr, $dom = null, $node = null, $root = 'xml', $cdata = false)
    {
        $xml = [];
        foreach ($arr as $key => $val) {
            if(is_array($val)) {
                $xml[] = $this->arrayToXml($val, null, null, $key);
            } else {
                $xml[] = '<'.$key.'>'.$val.'</'.$key.'>';
            }
        }

        return '<'.$root.'>'.implode('', $xml).'</'.$root.'>';
    }

    /**
     * 验证接口返回数据
     * @param $response
     * @throws RequestException
     */
    protected function checkResponse($response)
    {
        if($response['RETURN_CODE'] != '0000') {
            throw new RequestException($response['RETURN_MSG']);
        }
    }

    /**
     * 获取响应数据（无需获取，只做上传操作）
     * @return mixed
     */
    public function getResponse()
    {
        return true;
    }

    /**
     * @param mixed $response
     * @throws \request\RequestException
     */
    public function setResponse($response)
    {
        $response = base64_decode($response);
        $objectXml = simplexml_load_string($response);//将文件转换成 对象
        $xmlJson = json_encode($objectXml);//将对象转换个JSON
        $this->response = json_decode($xmlJson,true);//将json转换成数组

        $this->response = $this->response['BODY'];

        $this->checkResponse($this->response);
    }
}